package com.aispeech.lyra.nativec;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.aispeech.lyra.nativec.opensles.AudioDataSaver;
import com.aispeech.lyra.nativec.opensles.CRecorder;

import java.io.File;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {


    private CRecorder recorder;
    private String TAG = getClass().getSimpleName();
    private final int requestId = 123;
    private TextView tv;
    private EditText nameEditText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = findViewById(R.id.sample_text);
        tv.setMovementMethod(new ScrollingMovementMethod());
        nameEditText = findViewById(R.id.nameEditText);
        recorder = new CRecorder();
        tv.setText("音频保存目录：" + AudioDataSaver.instance.pcmFolder);
        showRercordStatus();
        requestPermission();
        Log.w(TAG, "onCreate called  ");
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        Log.d(TAG, "onRequestPermissionsResult");
        switch (requestCode) {
            case requestId: {
                for (int result : grantResults) {
                    if (result != PackageManager.PERMISSION_GRANTED) {
                        requestPermission();
                    }
                }
            }
        }
    }


    private void requestPermission() {
        ArrayList<String> requestList = new ArrayList<>();
        String[] permissions = new String[]{Manifest.permission.RECORD_AUDIO,
                Manifest.permission.WRITE_EXTERNAL_STORAGE};
        Log.d(TAG, "requestPermission");
        for (String perm : permissions) {
            if (ContextCompat.checkSelfPermission(this, perm) != PackageManager.PERMISSION_GRANTED) {
                requestList.add(perm);
                Log.d(TAG, "requestPermission:" + perm);
            }
            if (!requestList.isEmpty()) {
                ActivityCompat.requestPermissions(this, permissions, requestId);
            }
        }
    }


    public void onBTClick1(View view) {
        final String input = nameEditText.getText().toString();
        new Thread(new Runnable() {
            @Override
            public void run() {
                AudioDataSaver.instance.inputname=input;
                AudioDataSaver.instance.setAllowSaving(true);
                if (recorder.isInRecording()) {
                    showTip("录音中！！！，文件名："+input);
                }else {
                    showTip("初始化  开始录音！！！，文件名："+input);
                }
                recorder.initRecordConfigIfNeed();
                recorder.startRecord();

            }
        }).start();

        showRercordStatus();
    }

    public void onBTClick2(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (!recorder.isInRecording()) {
                    showTip("没有在录音哦！");
                    return;
                }
                recorder.stopRecord();
                showTip("结束录音！！");
                AudioDataSaver.instance.stopSave();
                AudioDataSaver.instance.setAllowSaving(false);
            }
        }).start();
        showRercordStatus();
    }

    public void onBTClick3(View view) {
        tv.setText("已清空");
        File folderFile = new File(AudioDataSaver.instance.pcmFolder);
        if (folderFile == null) {
            return;
        }
        try {
            File[] allFiles = folderFile.listFiles();
            if(allFiles==null){
                Log.e(TAG, "allFiles is null");
                showTip("已删除");
                return;
            }
            for (File tmpFile : allFiles) {
                if(tmpFile !=null){
                    tmpFile.delete();
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    private void showRercordStatus() {

        tv.postDelayed(new Runnable() {
            @Override
            public void run() {
                tv.append("\n是否在录音中：" + recorder.isInRecording() +",最近的录音文件名:"+AudioDataSaver.instance.fullName);
            }
        }, 500);
    }


    private void showTip(final CharSequence text) {
        tv.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplication(), text, Toast.LENGTH_SHORT).show();
            }
        });

    }
}
